<template>
    <basic-container>
        <div class="flex-center container">
            <div class="position-center" v-if="mapLoading === true">
                <div class="f-s-16"><i class="el-icon-loading"></i>加载地图中...</div>
            </div>
            <div v-show="mapLoading === false" class="w-100 h-100">
                <div id="_mt_amap"></div>
                <div class="__nav flex-start">
                    <el-button size="small" type="primary" icon="el-icon-search" :loading="queryLoading"
                               @click="doQuery">查询
                    </el-button>
                    <div class="m-l-20 f-g-1" style="z-index: 1000">
                        <app-address @output="regionChange"/>
                    </div>
                </div>
                <div class="__table">
                    <div>
                        <div class="flex-end">
                            <el-card style="width: 180px; cursor: pointer">
                                <div class="pa-8" @click="hideWarnFlag=!hideWarnFlag">
                                    <i class="el-icon-bell f-s-20 c-red m-r-10"
                                       style="position: relative;top: 2px;"></i>
                                    <span class="f-s-14 m-r-5">库存预警</span>
                                    <el-badge :value="warnMachineList.length" class="m-r-20"/>
                                    <el-button class="f-s-20"
                                               style="position: relative;top:2px; padding: 0;margin-right: -10px;"
                                               type="text"
                                               :icon="hideWarnFlag ? 'el-icon-arrow-down':'el-icon-arrow-up'"/>
                                </div>
                            </el-card>
                        </div>
                        <div class="flex-end">
                            <el-card class="m-t-10" style="width: 780px;" v-show="hideWarnFlag===false">
                                <el-table class="my-table" :data="warnMachineList" border height="350px"
                                          :header-cell-style="{background:'#eee',color:'#000'}">
                                    <el-table-column type="index" align="center" label="序号" width="60"/>
                                    <el-table-column prop="macCode" label="加注机编号" width="160">
                                        <template v-slot="scope">
                                            <el-button type="text" size="mini" class="f-s-12"
                                                       @click="mapTo(scope.row,'warn')">{{ scope.row.macCode }}
                                            </el-button>
                                        </template>
                                    </el-table-column>
                                    <el-table-column prop="siteName" label="加注站名称" min-width="160"/>
                                    <el-table-column label="桶容量（吨）" width="120">
                                        <template v-slot="scope">{{ scope.row.totalCapacity | kg2Tons }}</template>
                                    </el-table-column>
                                    <el-table-column label="余量（吨）" width="120">
                                        <template v-slot="scope">{{ scope.row.currentCapacity | kg2Tons }}</template>
                                    </el-table-column>
                                    <el-table-column prop="percentage" label="余量（%）" width="120"/>
                                </el-table>
                            </el-card>
                        </div>
                        <div class="flex-end m-t-10">
                            <el-card style="width: 180px; cursor: pointer">
                                <div class="pa-8" @click="hideOrderFlag=!hideOrderFlag">
                                    <i class="el-icon-tickets f-s-20 c-blue m-r-10"
                                       style="position: relative;top: 2px;"></i>
                                    <span class="f-s-14 m-r-5">当前工单</span>
                                    <el-badge type="primary" :value="fillMachineList.length" class="m-r-20"/>
                                    <el-button class="f-s-20"
                                               style="position: relative;top:2px; padding: 0;margin-right: -10px;"
                                               type="text"
                                               :icon="hideOrderFlag ? 'el-icon-arrow-down':'el-icon-arrow-up'"/>
                                </div>
                            </el-card>
                        </div>
                        <el-card class="m-t-10" style="width: 980px;" v-show="hideOrderFlag===false">
                            <el-table v-if="refreshFlag>0" class="my-table" :data="fillMachineList" border height="350"
                                      :header-cell-style="{background:'#eee',color:'#000'}">
                                <el-table-column type="index" align="center" label="序号" width="60"/>
                                <el-table-column label="加注机编号" width="130">
                                    <template v-slot="scope">
                                        <el-button type="text" size="mini" class="f-s-12"
                                                   @click="mapTo(scope.row,'select')">{{ scope.row.macCode }}
                                        </el-button>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="siteName" label="加注站名称" min-width="160"/>
                                <el-table-column label="所在集群" min-width="130">
                                    <template v-slot="scope">
                                        <div>{{ scope.row.clusterName | defaultValue }}</div>
                                    </template>
                                </el-table-column>
                                <el-table-column label="总容量（吨）" width="120">
                                    <template v-slot="scope">{{ scope.row.totalCapacity | kg2Tons }}</template>
                                </el-table-column>
                                <el-table-column label="理论余量（吨）" width="140">
                                    <template v-slot="scope">{{ scope.row.currentCapacity | kg2Tons }}</template>
                                </el-table-column>
                                <el-table-column label="本次补液量（吨）" width="210">
                                    <template v-slot="scope">
                                        <el-input-number :min="0" size="small" class="m-r-10"
                                                         :step="0.01"
                                                         v-model="fillMachineList[scope.$index].expectCapacity"
                                                         :max="fillMachineList[scope.$index]._maxCapacity"
                                                         @change="capacityChange"/>
                                        <el-button size="mini" circle icon="el-icon-minus" type="primary"
                                                   @click="removeMachine(scope.$index)"/>
                                    </template>
                                </el-table-column>
                            </el-table>
                            <div class="dividing-line m-t-10"></div>
                            <div class="flex-center pa-12">
                                <div>
                                    预计补液量（吨）： {{ total | kg2Tons }}
                                </div>
                                <div class="flex-center">
                                    <el-button size="mini" @click="hideOrderFlag=true">取消</el-button>
                                    <auth-wrapper btn-key="map-ticket:create">
                                        <el-button size="mini" :loading="loading" @click="doConfirm" type="primary">生成
                                        </el-button>
                                    </auth-wrapper>
                                </div>
                            </div>
                        </el-card>
                    </div>
                </div>
            </div>
        </div>
    </basic-container>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";
import {mapConfig} from "@/components/business/map-config";
import {
    getRespData,
    isListEmpty,
    isNumberValue,
    msgError,
    equals,
    isNotNull,
    msgSuccess,
    isNull, isTrue, listNotEmpty, isStringEmpty, listRemove
} from "@/util/common-util";
import AppAddress from "@/components/business/app-address";
import {getAllBySearch, getSyncAll} from "@/api/business/filling-machine";
import {save} from "@/api/business/filling-storage-order";
import AuthWrapper from "@/components/business/auth-wrapper";

export default {
    name: "index",
    components: {AuthWrapper, AppAddress},
    data() {
        return {
            queryLoading: false,
            mapLoading: false,
            curLocation: [117.230799, 31.852396],
            pixel: [],
            hideWarnFlag: true,
            hideOrderFlag: true,
            warnMachineList: [],
            fillMachineList: [],
            queryMachineList: [],
            search: {
                partnerId: '',
                districtCode: null,
                cityCode: null,
                provinceCode: null,
                clusterId: null
            },
            total: 0,
            loading: false,
            refreshFlag: 1,
            selectMachineCode: '',
            map: {},
            district: {},
            polygons: [],
            makerList: []
        }
    },
    created() {
    },
    async mounted() {
        await this.initFillingMachines()
        await this.initMap()
        window.closeInfoWindow = this.closeInfoWindow
        window.doPutFillList = this.doPutFillList
        window.showClusterMachineList = this.showClusterMachineList

        //行政区划查询
        this.district = new AMap.DistrictSearch({
            extensions: "all", // 是否返回行政区边界坐标点
            level: "city",     // 设置查询行政区级别为 区
        })
    },
    beforeDestroy() {
        this.map && this.map.destroy();
    },
    methods: {
        doQuery() {
            if (isStringEmpty(this.search.clusterId) && isStringEmpty(this.search.cityCode) && isStringEmpty(this.search.partnerId)
                && isStringEmpty(this.search.districtCode) && isStringEmpty(this.search.provinceCode)) {
                this.initFillingMachines(() => {
                    this.createMarkers()
                    this.map.remove(this.polygons)
                    this.map.setZoom(5)
                })
            } else {
                this.query(this.search)
            }
        },
        async initFillingMachines(success) {
            await getSyncAll().then(res => {
                this.warnMachineList = getRespData(res)
                this.queryMachineList = this.warnMachineList
                success && success()
            })
        },
        async initMap() {
            this.mapLoading = true
            await AMapLoader.load({
                "key": mapConfig.key,                       // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
                "plugins": ['AMap.Geocoder', 'AMap.DistrictSearch', 'AMap.Polygon'],           // 需要使用的的插件列表，如比例尺'AMap.Scale'等
            }).then((AMap) => {
                this.map = new AMap.Map('_mt_amap', {
                    zoom: 5,
                    center: this.curLocation
                })
                this.mapLoading = false
                this.createMarkers()
            }).catch(e => {
                console.error(e);
                msgError("加载地图失败")
                this.mapLoading = false
            })
        },
        regionChange(_region) {
            this.search.provinceCode = null
            this.search.cityCode = null
            this.search.districtCode = null
            if (isNull(_region)) return
            if (isNotNull(_region.area)) {
                this.setLocation(_region.area.value)
                this.search.provinceCode = _region.province.key
                this.search.cityCode = _region.city.key
                this.search.districtCode = _region.area.key
                this.query()
                return
            }
            if (isNotNull(_region.city)) {
                this.setLocation(_region.city.value)
                this.search.provinceCode = _region.province.key
                this.search.cityCode = _region.city.key
                this.query()
                return
            }
            if (isNotNull(_region.province)) {
                this.setLocation(_region.province.value)
                this.search.provinceCode = _region.province.key
                this.query()
                return
            }
            this.map.setZoom(5)
            this.doQuery()
        },
        setLocation(name) {
            const that = this
            //注意：需要使用插件同步下发功能才能这样直接使用
            this.district.search(name, function (status, result) {
                if (status == 'complete') getData(result.districtList[0])
            })
            this.map.setCity(name)
            this.map.remove(this.polygons)
            this.polygons = []

            function getData(data, level) {
                const bounds = data.boundaries;
                if (bounds) {
                    for (let i = 0, l = bounds.length; i < l; i++) {
                        that.polygons.push(new AMap.Polygon({
                            map: that.map,
                            strokeWeight: 1,
                            strokeColor: '#0091ea',
                            fillColor: '#80d8ff',
                            fillOpacity: 0.2,
                            path: bounds[i]
                        }));
                    }
                }
            }
        },
        createMarkers() {
            this.clearMarker()
            if (isListEmpty(this.queryMachineList)) return
            for (const item of this.queryMachineList) {
                item.percentage = '-'
                if (!isNumberValue(item.currentCapacity) && !isNumberValue(item.totalCapacity)) {
                    item.percentage = (Number(item.currentCapacity) * 100 / Number(item.totalCapacity)).toFixed(1)
                }
            }
            if (isListEmpty(this.queryMachineList)) return
            for (const item of this.queryMachineList) {
                this.createMarker(item)
            }
        },
        query(_search, success) {
            if (isNull(_search)) {
                _search = this.search
            }
            this.queryLoading = true
            getAllBySearch(_search).then(res => {
                this.queryLoading = false
                this.queryMachineList = getRespData(res)
                this.createMarkers()
                if (!isListEmpty(this.queryMachineList)) {
                    for (const item of this.queryMachineList) {
                        if (isNotNull(item.siteLng) && isNotNull(item.siteLat)) {
                            this.map.setZoom(12)
                            this.map.setCenter([item.siteLng, item.siteLat])
                        }
                    }
                }
                success && success()
            }).catch(() => {
                this.queryLoading = false
            })
        },
        clearMarker() {
            this.map.remove(this.makerList)
            this.makerList = []
        },
        createMarker(item) {
            try {
                let {siteLat, siteLng, percentage, warnValue, alarmValue} = item
                if (isNull(siteLat) && isNull(siteLng)) {
                    msgError("加注机" + item.macCode + "经纬度为空")
                    return
                }
                let ballClazz = 'ball-b'
                if (Number(percentage) < Number(alarmValue)) {
                    ballClazz = 'ball-p'
                } else if (Number(percentage) < Number(warnValue)) {
                    ballClazz = 'ball-r'
                }
                const marker = new AMap.Text({
                    text: `<div id="${item.macCode}" class="${ballClazz}">${percentage}%</div>`,
                    anchor: 'center', // 设置文本标记锚点
                    cursor: 'pointer',
                    position: new AMap.LngLat(siteLng, siteLat),
                    extData: item,
                    style: {'background-color': 'unset', 'border': 0},
                })
                this.makerList.push(marker)
                marker.setMap(this.map)
                marker.on('click', (e) => {
                    const {id} = e.target.getExtData()
                    this.openDetailInfo(e.target.getExtData())
                })
            } catch (e) {
                console.error(e)
            }
        },
        openDetailInfo(item) {
            let {siteLng, siteLat} = item;
            const infoWindow = new AMap.InfoWindow({
                content: this.infoWindowTemplate(item), //使用默认信息窗体框样式，显示信息内容
                isCustom: true, //使用自定义窗体,
                position: new AMap.LngLat(siteLng, siteLat),
                offset: new AMap.Pixel(150, 270),
            })
            infoWindow.open(this.map)
        },
        infoWindowTemplate(item) {
            let {siteName, macCode, currentCapacity, totalCapacity, clusterId} = item
            // todo tons
            currentCapacity = (Number(currentCapacity) / 1000).toFixed(2)
            totalCapacity = (Number(totalCapacity) / 1000).toFixed(2)
            const re = `<div class="site-card2 pa-16">
                <div class="flex-center">
                  <div class="f-s-16 f-w-600">${macCode || '--'}</div>
                  <div class="close-btn" onclick="closeInfoWindow()">X</div>
                </div>
                <div class="flex-start">
                  <div class="tag m-t-5">${siteName || '--'}</div>
                </div>
                <div class="flex-start m-t-20">
                    <div class="m-r-10">容量（吨）:</div>
                    <div>${currentCapacity}</div>
                </div>
                <div class="flex-start m-t-10">
                    <div class="m-r-10">余量（吨）:</div>
                    <div>${totalCapacity}</div>
                </div>
                <div class="dividing-line m-t-20"></div>
                <div class="btn m-t-10" onclick="doPutFillList('${macCode}')">补液</div>`
            if (isStringEmpty(clusterId)) {
                return re + '</div>'
            } else {
                return re + ` <div class="btn2 m-t-10" onclick="showClusterMachineList('${clusterId}')">该集群机器库存</div>
              </div>`
            }
        },
        closeInfoWindow() {
            this.map.clearInfoWindow();
        },
        doPutFillList(macCode) {
            for (const item of this.fillMachineList) {
                if (equals(macCode, item.macCode)) return
            }
            let re = null
            for (const item of this.warnMachineList) {
                if (equals(item.macCode, macCode)) {
                    re = item
                    break
                }
            }
            for (const item of this.queryMachineList) {
                if (equals(item.macCode, macCode)) {
                    re = item
                    break
                }
            }
            if (isNotNull(re)) {
                this.fillMachineList.push(re)
                this.computeCapacity(re)
            }
            this.map.clearInfoWindow();
        },
        computeCapacity(item) {
            const v = (Number(item.totalCapacity) - Number(item.currentCapacity)) * (100 + Number(item.floatRate)) / 100
            item.expectCapacity = Math.floor((v < 0 ? 0 : v) / 1000 * 100) / 100
            item._maxCapacity = item.expectCapacity
            this.capacityChange()
        },
        capacityChange() {
            this.total = 0
            for (const item of this.fillMachineList) {
                this.total += item.expectCapacity
            }
            this.refreshFlag = 0
            this.$nextTick(() => {
                this.refreshFlag = 1
            })
        },
        removeMachine(index) {
            listRemove(this.fillMachineList, index)
        },
        doConfirm() {
            const param = []
            for (const item of this.fillMachineList) {
                param.push({
                    siteId: item.siteId,
                    siteName: item.siteName,
                    macCode: item.macCode,
                    machineId: item.id,
                    expectCapacity: Math.floor(item.expectCapacity * 1000)
                })
            }
            if (isListEmpty(param)) return msgError("请选择加注机")
            this.loading = true
            save({fillStorageOrderDetailDTOList: param}).then(res => {
                msgSuccess()
                this.loading = false
                this.hideOrderFlag = true
                this.fillMachineList = []
            }).catch(() => {
                this.loading = false
            })
        },
        mapTo(row, type) {
            if (type === 'warn') {
                this.queryMachineList = this.warnMachineList
            }
            if (type === 'select') {
                this.queryMachineList = this.fillMachineList
            }
            this.createMarkers()
            let marker = document.getElementById(this.selectMachineCode);
            if (isNotNull(marker)) {
                marker.style.borderColor = '#fff';
            }
            this.selectMachineCode = row.macCode
            marker = document.getElementById(this.selectMachineCode);
            if (isNotNull(marker)) {
                marker.style.borderColor = '#3a3535';
            }
            this.map.setZoom(12)
            this.map.setCenter([row.siteLng, row.siteLat])
            this.hideOrderFlag = true
            this.hideWarnFlag = true
        },
        showClusterMachineList(clusterId) {
            this.query({clusterId: clusterId}, () => {
                this.closeInfoWindow()
            })
        }
    }
}
</script>

<style lang="scss">

.ball-b, .ball-r, .ball-p {
    user-select: none;
    height: 50px;
    width: 50px;
    border-radius: 50%;
    border: 2px solid #FFFFFF;
    text-align: center;
    font-size: 14px;
    line-height: 50px;
    box-shadow: 0 2px 2px 2px rgba(0, 0, 0, 0.1);
    color: #FFFFFF;
}

.ball-b {
    background-color: #1e9fff;
}

.ball-r {
    background-color: #e56969;
}

.ball-p {
    background-color: #7d29e1;
}

.site-card2 {
    background: #ffffff;
    box-shadow: 0 2px 2px 2px rgba(0, 0, 0, 0.1);
    border-radius: 10px;
    min-height: 260px;
    width: 180px;

    .close-btn {
        border-radius: 50%;
        width: 24px;
        height: 24px;
        line-height: 24px;
        text-align: center;
        font-size: 12px;
        background-color: #dddddd;
        cursor: pointer;
    }

    .close-btn:hover {
        color: #e56969;
    }

    .btn {
        background-color: #1e9fff;
        border-radius: 5px;
        width: 100px;
        height: 32px;
        line-height: 32px;
        color: #FFFFFF;
        text-align: center;
        font-size: 14px;
        cursor: pointer;
    }

    .btn:hover {
        background-color: #126caf;
    }

    .btn2 {
        color: #126caf;
        text-decoration: underline;
        font-size: 12px;
        cursor: pointer;
    }

    .btn2:hover {
        color: #1e9fff;
    }

    .tag {
        background-color: rgb(236, 245, 255);
        border-radius: 3px;
        padding: 4px 8px;
        font-size: 12px;
        line-height: 16px;
        color: #1e9fff;
        text-align: center;
    }
}

</style>


<style lang="scss" scoped>

.my-table {
    ::v-deep .el-button--small {
        padding: 0 5px !important;
        font-size: 14px !important;
    }

    ::v-deep td {
        padding: 8px 0 !important;
    }
}

::v-deep .el-card__body {
    padding: 5px;
}

.container {
    height: calc(100vh - 140px);
    position: relative;
}

.__nav {
    padding: 4px 12px;
    position: absolute;
    height: 50px;
    top: 0;
    left: 0;
    background-color: rgba(175, 170, 170, 0.16);

    ::v-deep .rg-select__content {
        background-color: #FFFFFF;
    }
}

.__table {
    padding: 12px;
    position: absolute;
    top: 0px;
    right: 0px;
    max-height: calc(100vh - 160px);
    //width: 10px;
    overflow-y: auto;
    overflow-x: hidden;
    background-color: rgba(175, 170, 170, 0.16);
}

.__marker {
    position: absolute;
    background-color: #1e9fff;
    width: 100px;
    height: 100px;
}

#_mt_amap {
    height: 100%;
    width: 100%;
}

.el-input {
    ::v-deep .el-input__inner {
        height: 35px;
    }
}
</style>

